import React from 'react';
import { Tree, Icon} from 'antd';
const TreeNode = Tree.TreeNode;
class SideBar extends React.Component {

  onLoadData = (treeNode) => {
    return new Promise((resolve) => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      this.props.loadChildTree(treeNode.props.dataRef.path, treeNode.props.dataRef.key);
      resolve();
    })
  }

  readData = (keys, e) => {
    if (e.selectedNodes[0] && e.selectedNodes[0].props.isLeaf) {
      const filePath = e.selectedNodes[0].props.path;
      const regex = /\.dat$/;
      if (regex.test(filePath)) {
        this.props.analysisData(filePath);
      }
    }
  }

  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      if (this.props.filterTag.length === 0) {
        if (this.props.jsonTree[item.path.slice(0, -3) + 'json']) {
          return <TreeNode icon={<Icon type="check" style={{ fontSize: 16, color: '#fff' }} />} {...item} dataRef={item} />;
        } else {
          return <TreeNode {...item} dataRef={item} />;
        }
      } else {
        const filterPath = [];
        const filterTag = this.props.filterTag;
        Object.values(this.props.jsonTree).forEach(ele => {
          let containerAllTags = true;
          for (let i = 0, len = filterTag.length; i < len; i++) {
            if (!ele.tags.includes(filterTag[i])) {
              containerAllTags = false;
            }       
          }
          if (containerAllTags) {
            filterPath.push(ele.path.slice(0, -4) + 'dat');
          }
        });
        if (filterPath.includes(item.path)) {
          if (this.props.jsonTree[item.path.slice(0, -3) + 'json']) {
            return <TreeNode icon={<Icon type="check" style={{ fontSize: 16, color: '#fff' }} />} {...item} dataRef={item} />;
          } else {
            return <TreeNode {...item} dataRef={item} />;
          }
        }
      }
    });
  }

  render() {
    return (
      <div id="left">
        <Tree showIcon loadData={this.onLoadData} onSelect={this.readData}>
          {this.renderTreeNodes(this.props.folderTree)}
        </Tree>
      </div>
    );
  }
}

export default SideBar;
